import {
  toDoCreateCategory,
  toDoCreateToDoItem,
  toDoDeleteItem,
  toDoDeleteItemCategory,
  toDoGetCustomerToDoItemCategory,
  toDoPage,
  toDoUpdateToDoItem,
  toDoUpdateToDoItemCompleted,
  toDoUpdateToDoItemPriority,
} from '@/services/swagger/toDo';
import { HeartFilled, HeartOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message, Select, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';

/**
 * @en-US Add Todo item
 * @zh-CN 添加代办项
 * @param fields
 */
const handleAdd = async (fields: API.ToDoItemCreateInputModel) => {
  const hide = message.loading('正在添加');
  try {
    await toDoCreateToDoItem({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Add Category
 * @zh-CN 添加类别
 * @param fields
 */
const handleCategoryAdd = async (fields: API.CategoryCreateInputModel) => {
  const hide = message.loading('正在添加');
  try {
    await toDoCreateCategory({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Update ToDo Item
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('Configuring');
  try {
    await toDoUpdateToDoItem(fields);
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请重试!');
    return false;
  }
};

/**
 * @en-US Update priority
 * @zh-CN 修改等级
 * @param fields
 */
const handlePriority = async (id: number, priority: number) => {
  const hide = message.loading('正在修改');
  try {
    await toDoUpdateToDoItemPriority({
      itemId: id as number,
      priorityType: priority as API.ToDoPriorityType,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Toggle completed
 * @zh-CN 是否完成
 * @param fields
 */
const handleToggleCompleted = async (fields: API.ToDoItemOutputModel) => {
  const hide = message.loading('正在修改');
  try {
    await toDoUpdateToDoItemCompleted({
      itemId: fields.id as number,
      isCompleted: !fields.isCompleted as boolean,
    });
    hide();
    if (!fields.isCompleted) {
      message.success('已完成');
    } else {
      message.success('未完成');
    }
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 *  Delete ToDo Item
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.ToDoItemOutputModel[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = {
      ids: selectedRows.map((row) => row.id).join(','),
    } as API.ToDoDeleteItemParams;

    await toDoDeleteItem(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败, 请再次重试！');
    return false;
  }
};

const removeTag = async (categoryId: number, itemId: any) => {
  const hide = message.loading('正在删除');
  try {
    await toDoDeleteItemCategory({ itemId: itemId, categoryId: categoryId });
    hide();
    message.success('删除成功！');
  } catch (error) {
    hide();
    message.error('删除失败，请重试！');
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [categoryModalOpen, handleCategoryModalOpen] = useState(false);

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.VocabularyOutputModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.VocabularyOutputModel[]>([]);
  const [toDoItemCategories, settoDoItemCategoriesData] = useState<API.CategoryOutputModel[]>([]);

  const getCategoriesData = async () => {
    try {
      const result = await toDoGetCustomerToDoItemCategory();
      const data = result.data as API.CategoryOutputModel[];
      settoDoItemCategoriesData(data);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    }
  };
  useEffect(() => {
    getCategoriesData(); // 调用数据获取函数
  }, []); // 空依赖数组表示该效果只在组件首次渲染时运行

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.ToDoItemOutputModel>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.title.titleLabel"
          defaultMessage="Title"
        />
      ),
      dataIndex: 'title',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.isCompleted.completedLabel"
          defaultMessage="Is completed"
        />
      ),
      dataIndex: 'isCompleted',
      valueType: 'select',
      valueEnum: {
        true: { text: '已完成' },
        false: { text: '未完成' },
      },
      render: (text, entity) => {
        return (
          <a
            onClick={() => {
              handleToggleCompleted(entity);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            {entity.isCompleted ? <HeartFilled style={{ color: 'red' }} /> : <HeartOutlined />}
          </a>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.priority" defaultMessage="Priority" />,
      dataIndex: 'priority',
      valueType: 'select',
      valueEnum: {
        1: { text: '高' },
        2: { text: '中' },
        3: { text: '低' },
      },
      render: (text, entity) => {
        return (
          <Select
            value={Number(entity.priority)} // 确保将text转为数字
            onChange={(value) => {
              handlePriority(entity.id as number, value as number);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
            placeholder="Select priority" // 可以添加一个占位符
          >
            <Select.Option value={1}>
              <FormattedMessage id="pages.searchTable.priority.high" defaultMessage="High" />
            </Select.Option>
            <Select.Option value={2}>
              <FormattedMessage id="pages.searchTable.priority.medium" defaultMessage="Medium" />
            </Select.Option>
            <Select.Option value={3}>
              <FormattedMessage id="pages.searchTable.priority.low" defaultMessage="Low" />
            </Select.Option>
          </Select>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: (
        <FormattedMessage id="pages.searchTable.todo.categories" defaultMessage="Categories" />
      ),
      sorter: true,
      dataIndex: 'categories',
      search: false,
      render: (text, entity) => {
        const categoryIds = entity.categories || []; // 处理可能为 null 或 undefined 的情况
        const displayedCategories = categoryIds.slice(0, 3);

        const getRandomColor = () => {
          const colors = [
            'magenta',
            'red',
            'volcano',
            'orange',
            'gold',
            'lime',
            'green',
            'cyan',
            'blue',
            'geekblue',
            'purple',
          ];

          // 生成一个随机索引并返回对应颜色
          const randomIndex = Math.floor(Math.random() * colors.length);
          return colors[randomIndex];
        };

        // 根据 IDs 查找对应的名称
        const displayedCategoryNames = displayedCategories
          .map((categoryId) => {
            const category = toDoItemCategories.find((cat) => cat.id === categoryId);
            return category ? category.name : ''; // 如果找到了 category，则返回其名称
          })
          .filter((name) => name); // 过滤掉未找到名称的情况

        return (
          <>
            {displayedCategoryNames.map((item, index) => (
              <Tag
                key={index}
                color={getRandomColor()}
                closable
                onClose={async () => {
                  await removeTag(categoryIds[index], entity.id);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                }}
              >
                {item}
              </Tag> // 使用 Tag 显示每个时间并设置颜色
            ))}
            {categoryIds.length > 3 && <span> +{categoryIds.length - 3}</span>}{' '}
            {/* 如果超过 3 个，显示剩余数量 */}
          </>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.remark" defaultMessage="remark" />,
      dataIndex: 'remark',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.dueDate" defaultMessage="dueDate" />,
      sorter: true,
      dataIndex: 'dueDate',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: (
        <FormattedMessage id="pages.searchTable.completedTime" defaultMessage="Completed time" />
      ),
      sorter: true,
      dataIndex: 'completedTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.created" defaultMessage="Created time" />,
      sorter: true,
      dataIndex: 'created',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.user.list.update" defaultMessage="Update" />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ToDoItemOutputModel, API.ToDoPageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.todo.item.list',
          defaultMessage: 'Todo item list',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleCategoryModalOpen(true);
            }}
          >
            <PlusOutlined />{' '}
            <FormattedMessage
              id="pages.searchTable.createForm.newCategory"
              defaultMessage="New Category"
            />
          </Button>,
        ]}
        request={toDoPage}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newTodoItem',
          defaultMessage: 'New todo item',
        })}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.ToDoItemCreateInputModel);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.todo.item.title"
                  defaultMessage="Title is required"
                />
              ),
            },
          ]}
          width="md"
          name="title"
        />

        <ProFormTextArea
          width="md"
          name="description"
          placeholder={intl.formatMessage({
            id: 'pages.searchTable.todo.item.description',
            defaultMessage: 'Description',
          })}
        />

        <ProFormDatePicker
          width="md"
          name="dueDate"
          label={intl.formatMessage({
            id: 'pages.searchTable.todo.item.dueDate',
            defaultMessage: 'Due Date',
          })}
          rules={[{ type: 'date', message: 'Please select a valid date!' }]}
        />

        <ProFormSelect
          width="md"
          name="priority"
          label={intl.formatMessage({
            id: 'pages.searchTable.todo.item.priority',
            defaultMessage: 'Priority',
          })}
          options={[
            { label: '高', value: 1 },
            { label: '中', value: 2 },
            { label: '低', value: 3 },
          ]}
          rules={[{ required: true, message: 'Priority is required' }]}
        />

        <ProFormSelect
          width="md"
          name="categories"
          label={intl.formatMessage({
            id: 'pages.searchTable.todo.item.categories',
            defaultMessage: 'Categories',
          })}
          options={toDoItemCategories.map((cat) => ({
            label: cat.name,
            value: cat.id,
          }))}
          mode="multiple" // 允许多选
          rules={[{ required: true, message: 'At least one category is required' }]}
        />
      </ModalForm>
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newCategory',
          defaultMessage: 'New category',
        })}
        width="400px"
        open={categoryModalOpen}
        onOpenChange={handleCategoryModalOpen}
        onFinish={async (value) => {
          const success = await handleCategoryAdd(value as API.CategoryCreateInputModel);
          if (success) {
            handleCategoryModalOpen(false);
            if (actionRef.current) {
              await getCategoriesData();
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.todo.item.categories.name"
                  defaultMessage="Name is required"
                />
              ),
            },
          ]}
          width="md"
          name="name"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        toDoItemCategories={toDoItemCategories}
      />
    </PageContainer>
  );
};

export default TableList;
